<script setup>
import { useUserStore } from '@/store/user'
import { WHITE_LIST } from '@/utils/constants'
import { onLaunch } from '@dcloudio/uni-app'
// 注册全局拦截器
let interceptorsRegistered = false

function registerInterceptors() {
  if (interceptorsRegistered)
    return
  interceptorsRegistered = true
  // 统一处理路由参数格式
  const normalizeRouteParams = (args) => {
    return typeof args === 'string' ? { url: args } : { ...args }
  }

  // 公共登录检查方法
  const checkLogin = () => {
    const userStore = useUserStore()
    return userStore.isLoggedIn
  }

  // 路由拦截器配置
  const routeInterceptors = {
    navigateTo: {
      invoke(args) {
        const params = normalizeRouteParams(args)

        if (!checkLogin() && !WHITE_LIST.some(path => params.url.includes(path))) {
          uni.navigateTo({ url: '/pages/login/index' })
          return false // 阻止原始跳转
        }
        return params // 允许原始跳转
      },
    },
    redirectTo: {
      invoke(args) {
        const params = normalizeRouteParams(args)

        if (!checkLogin() && !WHITE_LIST.some(path => params.url.includes(path))) {
          uni.redirectTo({ url: '/pages/login/index' })
          return false
        }
        return params
      },
    },
    reLaunch: {
      invoke(args) {
        const params = normalizeRouteParams(args)

        if (!checkLogin() && !WHITE_LIST.some(path => params.url.includes(path))) {
          uni.reLaunch({ url: '/pages/login/index' })
          return false
        }
        return params
      },
    },
    switchTab: {
      invoke(args) {
        const params = normalizeRouteParams(args)
        if (!checkLogin() && !WHITE_LIST.some(path => params.url.includes(path))) {
          // 注意：switchTab 无法跳转到非 tabBar 页面
          uni.reLaunch({ url: '/pages/login/index' })
          return false
        }
        return params
      },
    },
  }

  // 注册所有路由拦截器
  Object.entries(routeInterceptors).forEach(([apiName, interceptor]) => {
    uni.addInterceptor(apiName, interceptor)
  })
}

onLaunch(() => {
  // 必须在应用初始化后注册拦截器
  registerInterceptors()
})
</script>

<style></style>
